<template>
  <div class="banner">
    <img src="/static/imgs/index/banner.png" alt="" class="default-banner" v-if="isSliderLength">
    <ul v-else class="bannerimg-box flex" :style="containerStyle">
      <li v-for="(item, index) in sliders" :key="index">
        <img :src="item.image" alt="" @click="See(item.link,item.type,index)">
      </li>
      <li>
        <img :src="firstImg" alt="" @click="See(sliders[0].link,item.link_type)">
      </li>
    </ul>
    <ul class="bannernav flex">
      <li v-for="(dot, i) in sliders" :key="i" :class="{dotted: i === currentIndex}"></li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      sliders: [], //图片数据
      firstImg: "", //第一张图片
      currentIndex: 0, //轮播点
      distance: 0, //移动距离
      width: document.body.clientWidth, //动态获取宽度
      direction: -1,
      ulWidth: 1125,
      transition: "all .5s",
      isSliderLength:false,//无banner图返回时显示静态图的变量
    };
  },
  computed: {
    containerStyle() {
      return {
        left: `${this.distance}px`,
        transition: `${this.transition}`
      };
    }
  },
  mounted() {
    this.$util.get("index/bannerList").then(res => {
      this.sliders = res.data;
      if (this.sliders.length) {
        this.firstImg = this.sliders[0].image;
        setInterval(() => {
          this.move();
          this.currentIndex++;
          if (this.currentIndex === this.sliders.length) {
            this.currentIndex = 0;
          }
        }, 3000);
      }else{
        this.isSliderLength = true;
      }
    });
  },
  methods: {
    //点击banner跳转
    See(link, type, index) {
      switch (type) {
        case 3://无连接
          return;
          break;
        case 2:
          window.open(link);//跳转外部链接
          break;
        case 1:
        this.$router.push(`/details/${this.sliders[index].goodid}`)//跳转商品详情页
        default:
          break;
      }
    },
    move() {
      if (Math.abs(this.distance) == this.ulWidth) {
        this.transition = "none";
        this.distance = 0;
        setTimeout(() => {
          this.distance += this.direction * this.width;
          this.transition = "all 0.5s";
        }, 50);
      } else {
        this.distance += this.direction * this.width;
        this.transition = "all .5s";
      }
      return this.distance;
    }
  }
};
</script>
<style lang="less" scoped>
@import url(../../assets/css/index/banner.less);
</style>
